package com.newtouch.cq.base.starter.lang.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.newtouch.cq.base.starter.business.model.vo.BaseParentAble;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @date 2017年11月9日23:34:11
 */
public class TreeUtilParentAble {
	
	public static <T extends BaseParentAble<T>> List<T> buildTree(List<T> list){
		if(CollectionUtil.isEmpty(list)) {
			return list;
		}
		List<T> topList = new ArrayList<>();
		List<Long> idList = list.parallelStream().map(BaseParentAble::getId).collect(Collectors.toList());
		Iterator<T> iterator = list.iterator();
		for (; iterator.hasNext();) {
			T top = iterator.next();
			if(top.getParentId() < 0 || !idList.contains(top.getParentId())) {
				topList.add(top);
				iterator.remove();
			}
		}
		buildTree(topList, list);
		return topList;
	}
	
	public static <T extends BaseParentAble<T>> void buildTree(List<T> parentList, List<T> list){
		for (int i = 0; i < parentList.size(); i++) {
			T parent = parentList.get(i);
			for (int j = 0; j < list.size(); j++) {
				T child = list.get(j);
				if (ObjectUtil.equal(child.getParentId(),parent.getId())) {
					parent.addChild(child);
					list.remove(j);
					j--;
				}
			}
			if(CollectionUtil.isNotEmpty(parent.getChildren()) && list.size() > 0) {
				buildTree(parent.getChildren(), list);
			}
		}
	}
	
}
